package org.langcom;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class BloodLine<T> implements Serializable {

	private static final long serialVersionUID = -8022508829652693135L;
	private final List<T> bloodLine = new ArrayList<T>();

	public BloodLine(List<T> bloodLine) {
		this.bloodLine.addAll(bloodLine);
	}

	public BloodLine(T root) {
		this.bloodLine.add(root);
	}

	public BloodLine(T item, boolean explore) {
		try {
			explore(item);
		} catch (Exception e) {
			e.printStackTrace();
			bloodLine.add(0,item);
		}
	}

	public void explore(T item) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
		try {
			Method getParent = item.getClass().getMethod("getParent", new Class[0]); //$NON-NLS-1$
			if (getParent != null) {
				Object parent = getParent.invoke(item, new Object[0]);
				while (parent != null) {
					bloodLine.add(0, (T) parent);
					parent = getParent.invoke(parent, new Object[0]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}

	public boolean isRelative(List<T> kinLine) {
		for (T lineItem : bloodLine) {
			if (kinLine.contains(lineItem)) {
				return true;
			}
		}
		return false;
	}

	public List<T> getBloodLine() {
		return bloodLine;
	}

	@Override
	public String toString() {
		String result = ""; //$NON-NLS-1$
		for (T item : bloodLine) {
			result += " / " + item.toString(); //$NON-NLS-1$
		}
		return result;
	}

}
